package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etoak.common.core.excption.CustomExcetpion;
import com.etoak.common.core.vo.PageVO;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CancellationException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2024-12-18
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    @Autowired
    DishesMapper dishesMapper;

    @Override
    public boolean isIngredientsUsed(int id) {
        List<Dishes> list = lambdaQuery().eq(Dishes::getMain, id)
                .or()
                .eq(Dishes::getMinor, id)
                .or()
                .eq(Dishes::getSeasoning, id)
                .list(new Page<>(1,1));
        return CollectionUtils.isNotEmpty(list);
    }

    @Override
    public void add(Dishes dishes) {
        // 判断食材名称是否重复
        if (ObjectUtils.isNotEmpty(getByName(dishes.getName()))) {
            throw new CustomExcetpion("食材名称重复!");
        }

        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);
    }

    // 获取菜品列表
    @Override
    public PageVO<DishesVO> getList(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum,pageSize);
        List<DishesVO> list = dishesMapper.getList(dishes);
        PageInfo<DishesVO> pageInfo = new PageInfo<>(list);
        return new PageVO<>(pageInfo.getTotal(),list);
    }

    // 修改菜品
    @Override
    public void update(int id, Dishes dishes) {
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomExcetpion("菜品不存在!");
        }

        // 判断名称是否重复
        String name = dishes.getName();
        if (ObjectUtils.isNotEmpty(name)) {
            Dishes dishes1 = getByName(name);
            if (ObjectUtils.isNotEmpty(dishes1) && !dishes1.getId().equals(id)) {
                throw new CustomExcetpion("食材名称重复!");
            }
        }

        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);
    }

    // 删除菜品
    @Override
    public void delete(int id) {
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomExcetpion("菜品不存在!");
        }
        this.removeById(id);
    }

    private Dishes getByName( String name) {
        return lambdaQuery().eq(Dishes::getName,name).one();
    }
}
